//
//  RecommendListViewController.m
//  网络FM
//
//  Created by dllo on 15/5/23.
//  Copyright (c) 2015年 dengzhicheng.com. All rights reserved.
//

#import "RecommendListViewController.h"
#import "RecommendListTableViewCell.h"
#import <AFNetworking.h>
#import "RecommendListModel.h"
#import <UIImageView+WebCache.h>
#import "RecommendContentViewController.h"
#import <MJRefresh.h>
#import "GFPlaceholderView.h"
@interface RecommendListViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)NSMutableArray *bigArray;
@property (nonatomic, assign) NSInteger pageChanged;
@property (nonatomic, retain)GFPlaceholderView *placeholder;
@end

@implementation RecommendListViewController
- (void)dealloc
{
    [_topTitle release];
    [_lbid release];
    [_pagenum release];
    [_placeholder release];
    [_tableView release];
    [_bigArray release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.bigArray = [NSMutableArray array];
        self.pageChanged = 2;
    }
    return self;
}
- (void)ListTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    //上拉刷新下拉加载
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(Refresh)];
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(Load)];
    
    [self.view addSubview:_tableView];
    [_tableView release];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self recommendConnection];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    // 自定义导航栏返回按钮
    UIButton *navButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [navButton addTarget:self action:@selector(navButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [navButton setImage:[UIImage imageNamed:@"返回.jpg"] forState:UIControlStateNormal];
    [navButton setImage:[UIImage imageNamed:@"返回.jpg"] forState:UIControlStateHighlighted];
    [self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:navButton]];
    [navButton release];
    
    //等待界面
    self.placeholder = [[GFPlaceholderView alloc] initWithFrame:CGRectMake(0, - 64, self.view.frame.size.width, self.view.frame.size.height)];
    [_placeholder showLoadingView];
    [self.view addSubview:_placeholder];
    [_placeholder release];
    //设置导航标题
    self.navigationItem.title = self.topTitle;


}

// 导航栏返回按钮点击事件
- (void)navButtonClick:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark 上拉刷新 下拉加载
- (void)Refresh
{
    [self.tableView reloadData];
    [self.tableView.header endRefreshing];
}
- (void)Load
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *str = [NSString stringWithFormat:@"http://d.fm.ifeng.com/fm/read/fmd/ios/600/getLeaderboardList.html?appid=TRWLY&lbid=%@&token=nyfeSJPWN7HkQKQ8&pagenum=%ld", self.lbid,_pageChanged];
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableDictionary *dic = [bigDic objectForKey:@"data"];
        NSMutableArray *array = [dic objectForKey:@"programList"];
        //判断是否是最后一条
        if (array.count == 0) {
            [self.tableView removeFooter];
            return ;
        }
        //遍历存入model放入数组
        for (NSMutableDictionary *dictionary in array) {
            RecommendListModel *model = [[RecommendListModel alloc] init];
            [model setValuesForKeysWithDictionary:dictionary];
            [self.bigArray addObject:model];
            [model release];
        }
        self.pageChanged += 1;
        [self.tableView.footer endRefreshing];
        [self.tableView reloadData];
        
    } failure:
     ^(AFHTTPRequestOperation *operation, NSError *error) {
         [self.tableView.footer endRefreshing];
     }];
}



#pragma mark -
#pragma mark 创建Cell
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.bigArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"ListCell";
    RecommendListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (!cell) {
        cell = [[RecommendListTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:str];
    }
        RecommendListModel *model = [self.bigArray objectAtIndex:indexPath.row];
        [cell.numberLable setText:[NSString stringWithFormat:@"%ld", indexPath.row + 1]];
        [cell.listImageView sd_setImageWithURL:[NSURL URLWithString:model.img194_194] placeholderImage:[UIImage imageNamed:@"占位图.jpg"] options:SDWebImageRetryFailed];
        [cell.titleLable setText:model.programName];
        [cell.mainLable setText:model.sourceDetails];

    
    if (indexPath.row % 2) {
        
        cell.frame = CGRectMake(-320, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        
        [UIView animateWithDuration:0.7 animations:^{
            cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        } completion:^(BOOL finished) {
            ;
        }];
        
    }
    else{
        
        cell.frame = CGRectMake(320 ,cell.frame.origin.y ,cell.frame.size.width, cell.frame.size.height);
        
        [UIView animateWithDuration:0.7 animations:^{
            cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        } completion:^(BOOL finished) {
            ;
        }];
        
    }
    return cell;
}
#pragma mark -
#pragma mark 数据请求
- (void)recommendConnection
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *str = [NSString stringWithFormat:@"http://d.fm.ifeng.com/fm/read/fmd/ios/600/getLeaderboardList.html?appid=TRWLY&lbid=%@&token=nyfeSJPWN7HkQKQ8", self.lbid];
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableDictionary *dic = [bigDic objectForKey:@"data"];
        NSMutableArray *array = [dic objectForKey:@"programList"];
        //遍历存入model放入数组
        for (NSMutableDictionary *dictionary in array) {
            RecommendListModel *model = [[RecommendListModel alloc] init];
            [model setValuesForKeysWithDictionary:dictionary];
            [self.bigArray addObject:model];
            [model release];
        }
        //请求完毕再创建tableView
        [self ListTableView];
        
    } failure:
     ^(AFHTTPRequestOperation *operation, NSError *error) {
         
     }];
    
}
//cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}
#pragma mark -
#pragma mark Cell的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
    RecommendContentViewController *content = [[RecommendContentViewController alloc] init];
    RecommendListModel *model = [self.bigArray objectAtIndex:indexPath.row];
    content.pagenum = model.sort;
    content.pid = model.ID;
    content.contentTitle = model.programName;
    content.titleImage = model.img370_370;
    content.compere = model.compere;
    [self.navigationController pushViewController:content animated:YES];
    [content release];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
